﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UIPanel_Game : UIPanelBase {
    Transform panelRoot;
    Transform panelBack;
    Transform panelItemRoot;
    Transform txtStep;
    Transform txtTime;
    Dictionary<int, Sprite> sprites;

    Transform btnTip;
    Transform imgTip;
    Transform btnPause;
    Transform btnRestart;
    Transform btnSetting;
    Transform btnQuit;

    //Texture2D curT2d;
    GameMode curGm;
    string texHash;
    bool isPause = false;

    public override void OnInit(Transform root)
    {
        base.OnInit(root);
        panelRoot = root;
        InitGameObj();
        InitEvent();
        CommandController.instance.RegCommandEvent(OnCommandActionTriger);
        
    }

    void InitGameObj()
    {
        panelBack = panelRoot.Find("btn_home");
        panelItemRoot = panelRoot.Find("Panel_items");
        txtStep = panelRoot.Find("Panel_game_data/img_step/txt_step_count");
        txtTime = panelRoot.Find("Panel_game_data/img_time/txt_time_data");
        btnTip = panelRoot.Find("btn_tip");
        imgTip = panelRoot.Find("img_tip");

        btnPause = panelRoot.Find("btn_pause");
        btnRestart = panelRoot.Find("btn_restart");
        btnSetting = panelRoot.Find("btn_setting");
        btnQuit = panelRoot.Find("btn_quit");

        imgTip.gameObject.SetActive(false);
    }

    void InitEvent()
    {
        Button btn_back = panelBack.GetComponent<Button>();
        btn_back.onClick.RemoveAllListeners();
        btn_back.onClick.AddListener(Back);
        UIHoverListener.RegHoverEvent(btnTip.gameObject,(pd)=>{ TipSwitch(true); },(pd)=> { TipSwitch(false); });

        Button btn_pause = btnPause.GetComponent<Button>();
        btn_pause.onClick.RemoveAllListeners();
        btn_pause.onClick.AddListener(Pause);

        Button btn_restart = btnRestart.GetComponent<Button>();
        btn_restart.onClick.RemoveAllListeners();
        btn_restart.onClick.AddListener(Restart);

        Button btn_setting = btnSetting.GetComponent<Button>();
        btn_setting.onClick.RemoveAllListeners();
        btn_setting.onClick.AddListener(Setting);

        Button btn_quit = btnQuit.GetComponent<Button>();
        btn_quit.onClick.RemoveAllListeners();
        btn_quit.onClick.AddListener(Quit);

        Schedule.instance.AddTimer(0.1f, false, () => {
            txtStep.GetComponent<CustomNumberText>().text = GameController.instance.GetCurUseStep() + "b";
        });
    }

    public void StartGame(Texture2D t2d,GameMode gm)
    {
        curGm = gm;
        if (t2d != null)
        {
            byte[] bsPng = t2d.EncodeToPNG();
            texHash = FileUtil.GetMD5Hash(bsPng);
            Debug.Log("texHash:" + texHash);
            int row = 0;
            int col = 0;
            switch (gm)
            {
                case GameMode.Easy:
                    row = col = 3;
                    break;
                case GameMode.Normal:
                    row = col = 4;
                    break;
                case GameMode.Hard:
                    row = col = 5;
                    break;
            }

            sprites = TextureUtil.CreateSpitesByTexture(t2d, row, col);
            //List<int> listIndex = new List<int>(sprites.Keys);
            GameController.instance.Init(row, col);
            int[][] gridIndex = GameController.instance.GetCurGridIndex();
            FrashSprite( sprites, gridIndex);

            imgTip.GetComponent<Image>().sprite = Sprite.Create(t2d, new Rect(0,0, t2d.width, t2d.height),new Vector2(.5f,.5f));

        }
    }

    void Pause()
    {
        isPause = !isPause;
        GameController.instance.Pause(isPause);
        btnPause.GetComponent<Image>().enabled = true;
        btnPause.GetChild(0).GetComponent<Image>().enabled = true;
        Color c1 = Color.white;
        Color c2 = Color.white;
        c1.a = isPause? 0: 1;
        c2.a = !isPause ? 0 : 1;
        btnPause.GetComponent<Image>().color = c1;
        btnPause.GetChild(0).GetComponent<Image>().color = c2;
    }

    void Restart()
    {

    }

    void Setting()
    {
        UIManager.ShowUI<UIPanel_Setting>();
    }

    void Quit()
    {
        UIManager.ShowUI<UIPanel_Quit>();
    }

    void FrashSprite(Dictionary<int, Sprite> spDic,int[][] gridIndex)
    {
        int row, col;
        row = gridIndex.Length;
        col = gridIndex[0].Length;

        int cycleMaxCount = Mathf.Max(panelItemRoot.childCount, row* col);
        int initIndex = 0;

        Image panelRoot = panelItemRoot.GetComponent<Image>();
        float spWidth = panelRoot.rectTransform.sizeDelta.x / col;
        float spHeigt = panelRoot.rectTransform.sizeDelta.x / row;
        Vector2 posOffset = new Vector2(spWidth / 2f,-spHeigt/2);

        GameObject itemPrefab = panelItemRoot.GetChild(0).gameObject;
        for (int ir = 0; ir < row; ir++)
        {
            for (int ic = 0; ic < col; ic++)
            {
                int rowIndex = ir;
                int colIndex = ic;
                int spriteIndex = gridIndex[ir][ic];

                GameObject item = null;
                if (initIndex < panelItemRoot.childCount)
                {
                    item = panelItemRoot.GetChild(initIndex).gameObject;
                }
                else
                {
                    item = GameObject.Instantiate<GameObject>(itemPrefab); 
                    item.transform.SetParent(panelItemRoot,false);
                }
                item.transform.localScale = Vector3.one * 0.98f;
                Image img = item.GetComponent<Image>();
                img.rectTransform.sizeDelta = new Vector2(spWidth, spHeigt);
                img.color = Color.white;
                if (spriteIndex == 0)
                {
                    img.sprite = spDic[row * col];
                    Color c = Color.white;
                    c.a = 0.1f;
                    img.color = c;
                }
                else
                {
                    img.sprite = spDic[spriteIndex];
                }
                img.rectTransform.pivot = new Vector2(0.5f,0.5f);
                img.rectTransform.anchorMax = new Vector2(0,1);
                img.rectTransform.anchorMin = new Vector2(0,1);
                img.rectTransform.anchoredPosition = new Vector2(ic * spWidth, -ir* spHeigt)+ posOffset;
                //item.transform.Find("index").GetComponent<Text>().text = "" + spriteIndex;
                item.transform.Find("index").GetComponent<Text>().text = "" ;
                Button btnClick = item.GetComponent<Button>();
                if (btnClick == null)
                {
                    btnClick = item.AddComponent<Button>();
                }
                btnClick.onClick.RemoveAllListeners();
                btnClick.onClick.AddListener(()=> {
                    OnClickGridItem(row,col, rowIndex,colIndex);
                });
                initIndex++;
            }
        }
    }

    void OnClickGridItem(int row,int col, int rowIndex, int colIndex)
    {
        //Debug.LogError("rowIndex:" + rowIndex);
        //Debug.LogError("colIndex:" + colIndex);
        int[][] gridIndex = GameController.instance.GetCurGridIndex();
        CommandType ct = CommandType.None;
        //check up 
        if (rowIndex > 0)
        {
            if (gridIndex[rowIndex - 1][colIndex] == 0)
            {
                ct = CommandType.Up ;
            }
        }
        //check down 
        if (rowIndex +1< row)
        {
            if (gridIndex[rowIndex + 1][colIndex] == 0)
            {
                ct = CommandType.Down;
            }
        }
        //check left 
        if (colIndex>0)
        {
            if (gridIndex[rowIndex ][colIndex - 1] == 0)
            {
                ct = CommandType.Left;
            }
        }
        //check right 
        if (colIndex +1< col)
        {
            if (gridIndex[rowIndex][colIndex + 1] == 0)
            {
                ct = CommandType.Right;
            }
        }
        OnCommandActionTriger(ct);
    }

    void TipSwitch(bool state)
    {
        imgTip.gameObject.SetActive(state);
        GameController.pause = state;
    }


    void OnCommandActionTriger(CommandType ct)
    {
        if (GameController.pause) return;
        //Debug.LogError("ct:"+ ct);
        if (ct == CommandType.None) return;
        int[][] gridIndex = GameController.instance.GetCurGridIndex();
        gridIndex = GameController.instance.ExcuteCommand(ref gridIndex, ct);
        FrashSprite(sprites, gridIndex);
        bool isOver = GameController.instance.CheckIsGameOver();
        GameController.instance.StepOne();
        UpdateUI();
        //Debug.LogError("isOver:"+ isOver);
        // 播放胜利 动画
        if (isOver)
        {
            //清除当前关卡记录
            //记录完成数据 ，显示最佳和本次的对比数据
            UIManager.ShowUI<UIPanel_GameOver>(()=> {
                //UIManager.CloseUI<UIPanel_Game>();
                Pause();
                UIManager.GetUIPanelByType<UIPanel_GameOver>().OnGameOver(curGm, texHash,GameController.instance.GetCurUseStep(),GameController.instance.GetCurUseTime());
            });
        }
        else
        {
            //记录当前完成程度 
        }
        
    }

    void UpdateUI()
    {
        if (txtStep != null)
        {
            txtStep.GetComponent<CustomNumberText>().text = GameController.instance.GetCurUseStep()+"b";
        }
    }


    void Back()
    {
        UIManager.CloseUI<UIPanel_Game>();
        UIManager.ShowUI<UIPanel_Start>();
    }
    public override void Update()
    {
        base.Update();
        if (txtTime != null)
        {
            txtTime.GetComponent<CustomNumberText>().text = GameController.instance.GetCurUseTime().ToString()+"s";
        }
    }
    public override void OnClose()
    {
        base.OnClose();
        CommandController.instance.UnRegCommandEvent();
    }
}
